<template>
  <div style="width: 90vw; height: 50vh; background-color: #fff; border: 1px solid red;">
     <div ref="chart" class="chart-container" style="width: 100%; height: 100%;"></div>
  </div>
</template>

<script setup>
import { shallowRef , onMounted, defineProps, onBeforeUnmount, nextTick, reactive, toRefs, defineOptions, watch} from 'vue';
import * as echarts from 'echarts';


defineOptions({
  name: 'MyEchart',
});

const props = defineProps({
  option: {
    type: Object,
    required: true,
  },
  responsive: {
    type: Boolean,
    default: true,
  },
});
// const {option} = toRefs(props);
// 由于 Vue 3 的响应式系统使用了 Proxy，有时会导致与 ECharts 的交互出现问题
const chart = shallowRef(null)

onMounted(() => {
  nextTick(() => {
    console.log('确保dom加载完毕');
    chart.value = echarts.init(chart.value);
    renderChart();
  })
});
// 监听传进来配置项变化
watch(
  () => props.option,
  (newOption, oldOption) => {
    if (newOption !== oldOption) {
      renderChart();
    }
  }
);
const {TITLE_TEXT, LEGEND_DATA, XAXIS_DATA, SERIES, TYPE, GRAPHIC} = toRefs(props.option)
// 处理series 配置项
const NewSERIES = SERIES.value.map(item => {
  return {
    name: item.name || null, 
    type: TYPE.value || null, // 这里可以根据需要改为 'line' 或 'pie'
    data: item.data || null,
    radius: item.radius || null, // 定义同心圆圆角
    itemStyle: item.itemStyle || null, // 定义item 央视
    graphic: item.graphic || null, // 定义饼状图中间文字样式
    avoidLabelOverlap: item.avoidLabelOverlap || null, // 防止标签重叠 接受 true false
    label: item.label || null,  //配置饼状图周围是否显示标签
  }
})
console.log(NewSERIES, GRAPHIC, 'NewSERIES');
const ChartsConfig = {
  // 这里是ECharts的配置项
  title: {
    text: TITLE_TEXT.value ? TITLE_TEXT.value : null
  },
  legend: {
    data: XAXIS_DATA ? LEGEND_DATA.value : null
  },
  series: NewSERIES || null,
};
// 动态传递X Y轴配置项, 确保饼状图的时候不显示X,Y
if ( TYPE.value === 'line' && XAXIS_DATA ) {
  // line  就动态添加x , y 轴
  const Obj = {
    xAxis: {
      data: XAXIS_DATA
    },
    yAxis: {},
  }
  Object.assign(ChartsConfig, Obj)
} else if (TYPE.value === 'pie' && GRAPHIC) {
  // pie 根据需求动态添加中间文字效果
  const Obj = {
    graphic: GRAPHIC
  }
  Object.assign(ChartsConfig, Obj)
}
const chartOption = reactive(ChartsConfig);
const renderChart = () => {
  if (chart.value) {
    chart.value.setOption(chartOption);
  }
};
// Echarts 重置方法
const resizeChart = () => {
  if (chart.value) {
    chart.value.resize();
  }
};
// 配置是否监听窗口变化进行缩放
if (props.responsive) {
  window.addEventListener('resize', resizeChart);
  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeChart);
  });
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.chart-container {
  width: 100%;
  height: 100%;
  max-width: 100%;
  max-height: 100%;
}
</style>
